<?php

require "../../utility.php";
require "./book_utility.php";

function editBookInDb(mysqli $conn): bool {
    // 先检查 book id
    $id = "";
    if (check_keys($_POST, "id")) {
        $id = $_POST["id"];
    } else {
        return false;
    }

    $title_sql = "";
    if (check_keys($_POST, "title")) {
        $title = $_POST["title"];
        $title_sql = "title = '$title'";
    }

    $author_sql = "";
    if (check_keys($_POST, "author")) {
        $author = $_POST["author"];
        $author_sql = "author = '$author'";
    }

    $publisher_sql = "";
    if (check_keys($_POST, "publisher")) {
        $publisher = $_POST["publisher"];
        $publisher_sql = "publisher = '$publisher'";
    }

    $category_sql = "";
    if (check_keys($_POST, "category")) {
        $category = $_POST["category"];
        $category_sql = "category = '$category'";
    }

    $price_sql = "";
    if (check_keys($_POST, "price")) {
        $price = $_POST["price"];
        $price_sql = "price = $price";
    }

    $img_url_sql = "";
    if (check_keys($_FILES, "img")) {
        $img_url = storeImgToLocal();
        if ($img_url !== null) {
            $img_url_sql = "imgUrl = '$img_url'";
        } else {
            // 保存图片失败
            return false;
        }
    }

    // TODO: 理论上应该找到原来的图片并删除

    $set_str = "$title_sql,$author_sql,$publisher_sql,$category_sql,$price_sql,$img_url_sql";
    $len = strlen($set_str);
    // 去除前导 ','
    $idx = 0;
    while ($idx < $len && $set_str[$idx] == ',') {
        $set_str[$idx] = ' ';
        $idx += 1;
    }
    // 去除中间多余 ','
    for ($idx = 1; $idx < $len; $idx += 1) {
        if ($set_str[$idx - 1] == $set_str[$idx] && $set_str[$idx] == ',') {
            $set_str[$idx - 1] = ' ';
        }
    }
    // 去除尾部 ','
    $idx = $len - 1;
    while ($idx >= 0 && ($set_str[$idx] == ' ' || $set_str[$idx] == ',')) {
        $set_str[$idx] = ' ';
        $idx -= 1;
    }

    $update_str = "UPDATE Book SET $set_str WHERE ID = ?;";

    $update_stmt = $conn->prepare($update_str);
    $update_stmt->bind_param("i", $id);

    return $update_stmt->execute();
}



$conn = connect_mysql();
$user_id = getUserIdBySessionId($conn);

http_response_code(403);

// 先检查是否登录, 再检查用户权限
if ($user_id !== null &&
    getUserPermissionByUserId($conn, $user_id) >= 1) {
    // 再尝试修改数据库
    if (editBookInDb($conn)) {
        // 成功
        http_response_code(200);
    }
}

$conn->close();

?>